<template>
  <div class="dict-container">
    <el-page-header
      @back="$router.back()"
      content="数据字典管理"
    />

    <el-card class="mt-4">
      <!-- 标签页切换字典类型和字典项 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <!-- 字典类型管理 -->
        <el-tab-pane label="字典类型管理" name="types">
          <div class="flex justify-between items-center mb-4">
            <div class="flex gap-4">
              <el-input
                v-model="typeSearchQuery"
                placeholder="搜索字典类型名称或编码"
                clearable
                class="w-64"
                @clear="resetTypeSearch"
              >
                <template #append>
                  <el-button @click="handleTypeSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                </template>
              </el-input>
              <el-button @click="resetTypeSearch">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
            <el-button type="primary" @click="showCreateTypeDialog">
              <el-icon><Plus /></el-icon>
              新增字典类型
            </el-button>
          </div>

          <el-table
            v-loading="loadingTypes"
            :data="dictTypesData"
            style="width: 100%"
            border
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="字典名称" width="180" />
            <el-table-column prop="code" label="字典编码" width="180" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="is_active" label="状态" width="100">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.is_active"
                  active-text="启用"
                  inactive-text="禁用"
                  @change="handleTypeStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="sort_order" label="排序" width="100" />
            <el-table-column prop="created_at" label="创建时间" width="180" />
            <el-table-column prop="updated_at" label="更新时间" width="180" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                  type="primary"
                  link
                  @click="showEditTypeDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  @click="handleDeleteType(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="mt-4">
            <el-pagination
              v-model:current-page="typeCurrentPage"
              v-model:page-size="typePageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="typeTotal"
              @size-change="handleTypeSizeChange"
              @current-change="handleTypeCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 字典项管理 -->
        <el-tab-pane label="字典项管理" name="items">
          <div class="mb-4">
            <div class="flex justify-between items-center mb-4">
              <div class="flex gap-4">
                <el-select
                  v-model="selectedDictType"
                  placeholder="选择字典类型"
                  class="w-64"
                  @change="getDictItems"
                >
                  <el-option
                    v-for="type in dictTypes"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                  />
                </el-select>
                <el-input
                  v-model="itemSearchQuery"
                  placeholder="搜索字典项名称或值"
                  clearable
                  class="w-64"
                  @clear="resetItemSearch"
                >
                  <template #append>
                    <el-button @click="handleItemSearch">
                      <el-icon><Search /></el-icon>
                      搜索
                    </el-button>
                  </template>
                </el-input>
                <el-button @click="resetItemSearch">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
              <el-button
                type="primary"
                @click="showCreateItemDialog"
                :disabled="!selectedDictType"
              >
                <el-icon><Plus /></el-icon>
                新增字典项
              </el-button>
            </div>

            <el-table
              v-loading="loadingItems"
              :data="dictItemsData"
              style="width: 100%"
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="label" label="字典名称" width="180" />
              <el-table-column prop="value" label="字典值" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="is_active" label="状态" width="100">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.is_active"
                    active-text="启用"
                    inactive-text="禁用"
                    @change="handleItemStatusChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="sort_order" label="排序" width="100" />
              <el-table-column prop="created_at" label="创建时间" width="180" />
              <el-table-column prop="updated_at" label="更新时间" width="180" />
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button
                    type="primary"
                    link
                    @click="showEditItemDialog(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteItem(scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div class="mt-4">
              <el-pagination
                v-model:current-page="itemCurrentPage"
                v-model:page-size="itemPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="itemTotal"
                @size-change="handleItemSizeChange"
                @current-change="handleItemCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 创建/编辑字典类型对话框 -->
    <el-dialog
      v-model="typeDialogVisible"
      :title="typeDialogTitle"
      width="500px"
    >
      <el-form
        ref="typeFormRef"
        :model="typeForm"
        :rules="typeRules"
        label-width="120px"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input
            v-model="typeForm.name"
            placeholder="请输入字典名称"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input
            v-model="typeForm.code"
            placeholder="请输入字典编码（英文小写+下划线）"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="typeForm.description"
            placeholder="请输入描述"
            :maxlength="255"
            show-word-limit
            type="textarea"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number
            v-model="typeForm.sort_order"
            :min="0"
            :max="9999"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="typeForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeTypeDialog">取消</el-button>
          <el-button type="primary" @click="submitTypeForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 创建/编辑字典项对话框 -->
    <el-dialog
      v-model="itemDialogVisible"
      :title="itemDialogTitle"
      width="500px"
    >
      <el-form
        ref="itemFormRef"
        :model="itemForm"
        :rules="itemRules"
        label-width="120px"
      >
        <el-form-item label="字典类型" prop="dict_type_id">
          <el-select
            v-model="itemForm.dict_type_id"
            placeholder="请选择字典类型"
            disabled
          >
            <el-option
              v-for="type in dictTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字典名称" prop="label">
          <el-input
            v-model="itemForm.label"
            placeholder="请输入字典名称"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="字典值" prop="value">
          <el-input
            v-model="itemForm.value"
            placeholder="请输入字典值"
            :maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="itemForm.description"
            placeholder="请输入描述"
            :maxlength="255"
            show-word-limit
            type="textarea"
            rows="3"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number
            v-model="itemForm.sort_order"
            :min="0"
            :max="9999"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="itemForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeItemDialog">取消</el-button>
          <el-button type="primary" @click="submitItemForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import service from '@/utils/request'
import axios from 'axios'

const router = useRouter()

// 激活的标签页
const activeTab = ref('types')

// 字典类型相关状态
const dictTypes = ref([])
const dictTypesData = ref([])
const loadingTypes = ref(false)
const typeCurrentPage = ref(1)
const typePageSize = ref(10)
const typeTotal = ref(0)
const typeSearchQuery = ref('')
const typeSearchTimer = ref(null)

// 字典项相关状态
const selectedDictType = ref(null)
const dictItemsData = ref([])
const loadingItems = ref(false)
const itemCurrentPage = ref(1)
const itemPageSize = ref(10)
const itemTotal = ref(0)
const itemSearchQuery = ref('')
const itemSearchTimer = ref(null)

// 字典类型表单
const typeFormRef = ref(null)
const typeDialogVisible = ref(false)
const typeCurrentId = ref(null)
const typeForm = reactive({
  name: '',
  code: '',
  description: '',
  sort_order: 0,
  is_active: true
})
const typeRules = {
  name: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入字典编码', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-z_]+$/, message: '只能包含小写字母和下划线', trigger: 'blur' }
  ]
}

// 字典项表单
const itemFormRef = ref(null)
const itemDialogVisible = ref(false)
const itemCurrentId = ref(null)
const itemForm = reactive({
  dict_type_id: null,
  label: '',
  value: '',
  description: '',
  sort_order: 0,
  is_active: true
})
const itemRules = {
  label: [
    { required: true, message: '请输入字典名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入字典值', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const typeDialogTitle = computed(() => {
  return typeCurrentId.value ? '编辑字典类型' : '新增字典类型'
})
const itemDialogTitle = computed(() => {
  return itemCurrentId.value ? '编辑字典项' : '新增字典项'
})

// 生命周期
onMounted(() => {
  // 初始化加载字典类型数据
  getDictTypes()
})

// 获取字典类型列表
async function getDictTypes() {
  loadingTypes.value = true
  try {
    const response = await service.get('/dicts/types', {
      params: {
        skip: (typeCurrentPage.value - 1) * typePageSize.value,
        limit: typePageSize.value,
        is_active: null
      }
    })
    console.log('获取字典类型响应:', response)
    // 添加空值检查
    if (response!== undefined && response!== null && Array.isArray(response)) {
      dictTypes.value = response
      dictTypesData.value = response
      typeTotal.value = response.length
      
      // 当字典类型数据加载完成后，如果当前是字典项标签页且没有选中的字典类型，自动选择第一个
      if (activeTab.value === 'items' && !selectedDictType.value && response.length > 0) {
        selectedDictType.value = response[0].id
        // 等待selectedDictType更新后再加载字典项
        nextTick(() => {
          getDictItems()
        })
      } else if (selectedDictType.value && activeTab.value === 'items') {
        getDictItems()
      }
    } else {
      dictTypes.value = []
      dictTypesData.value = []
      typeTotal.value = 0
    }
  } catch (error) {
    console.error('获取字典类型异常:', error)
    dictTypes.value = []
    dictTypesData.value = []
    typeTotal.value = 0
    ElMessage.error('获取字典类型失败：' + (error.response?.data?.detail || error.message || '未知错误'))
  } finally {
    loadingTypes.value = false
  }
}

// 获取字典项列表
async function getDictItems() {
  if (!selectedDictType.value) return
  
  loadingItems.value = true
  try {
    const response = await service.get('/dicts/items', {
      params: {
        dict_type_id: selectedDictType.value,
        is_active: null
      }
    })
    // 添加空值检查
    if (response!== undefined && response!== null) {
      dictItemsData.value = response
      itemTotal.value = Array.isArray(response) ? response.length : 0 // 确保data是数组
    } else {
      dictItemsData.value = []
      itemTotal.value = 0
    }
  } catch (error) {
    console.error('获取字典项异常:', error)
    dictItemsData.value = []
    itemTotal.value = 0
    ElMessage.error('获取字典项失败：' + (error.response?.data?.detail || error.message || '未知错误'))
  } finally {
    loadingItems.value = false
  }
}

// 标签页切换处理
function handleTabClick(tab) {
  if (tab.paneName === 'items') {
    // 如果切换到字典项标签页，且没有选中的字典类型但有字典类型数据，自动选择第一个
    if (!selectedDictType.value && dictTypes.value.length > 0) {
      selectedDictType.value = dictTypes.value[0].id
      nextTick(() => {
        getDictItems()
      })
    } else if (selectedDictType.value) {
      getDictItems()
    }
  }
}

// 字典类型搜索
function handleTypeSearch() {
  if (typeSearchTimer.value) {
    clearTimeout(typeSearchTimer.value)
  }
  typeSearchTimer.value = setTimeout(() => {
    if (typeSearchQuery.value) {
      const filteredData = dictTypes.value.filter(item => 
        item.name.toLowerCase().includes(typeSearchQuery.value.toLowerCase()) ||
        item.code.toLowerCase().includes(typeSearchQuery.value.toLowerCase())
      )
      dictTypesData.value = filteredData
      typeTotal.value = filteredData.length
    } else {
      dictTypesData.value = dictTypes.value
      typeTotal.value = dictTypes.value.length
    }
  }, 300)
}

// 字典类型搜索重置
function resetTypeSearch() {
  typeSearchQuery.value = ''
  dictTypesData.value = dictTypes.value
  typeTotal.value = dictTypes.value.length
  if (typeSearchTimer.value) {
    clearTimeout(typeSearchTimer.value)
  }
}

// 字典项搜索
function handleItemSearch() {
  // 移除定时器，直接执行搜索
  if (itemSearchTimer.value) {
    clearTimeout(itemSearchTimer.value)
    itemSearchTimer.value = null
  }
  
  if (itemSearchQuery.value && dictItemsData.value.length > 0) {
    // 实现前端过滤搜索
    const filteredData = dictItemsData.value.filter(item => 
      item.label.toLowerCase().includes(itemSearchQuery.value.toLowerCase()) ||
      item.value.toLowerCase().includes(itemSearchQuery.value.toLowerCase())
    )
    dictItemsData.value = filteredData
    itemTotal.value = filteredData.length
  } else {
    // 重新加载原始数据
    getDictItems()
  }
}

// 字典项搜索重置
function resetItemSearch() {
  itemSearchQuery.value = ''
  if (selectedDictType.value) {
    getDictItems() // 重新加载数据
  }
  if (itemSearchTimer.value) {
    clearTimeout(itemSearchTimer.value)
  }
}

// 分页处理 - 字典类型
function handleTypeSizeChange(size) {
  typePageSize.value = size
  typeCurrentPage.value = 1
  getDictTypes()
}
function handleTypeCurrentChange(current) {
  typeCurrentPage.value = current
  getDictTypes()
}

// 分页处理 - 字典项
function handleItemSizeChange(size) {
  itemPageSize.value = size
  itemCurrentPage.value = 1
  getDictItems()
}
function handleItemCurrentChange(current) {
  itemCurrentPage.value = current
  getDictItems()
}

// 显示创建字典类型对话框
function showCreateTypeDialog() {
  typeCurrentId.value = null
  Object.assign(typeForm, {
    name: '',
    code: '',
    description: '',
    sort_order: 0,
    is_active: true
  })
  nextTick(() => {
    typeFormRef.value?.resetFields()
  })
  typeDialogVisible.value = true
}

// 显示编辑字典类型对话框
function showEditTypeDialog(row) {
  typeCurrentId.value = row.id
  Object.assign(typeForm, {
    name: row.name,
    code: row.code,
    description: row.description,
    sort_order: row.sort_order || 0,
    is_active: row.is_active
  })
  nextTick(() => {
    typeFormRef.value?.resetFields()
  })
  typeDialogVisible.value = true
}

// 关闭字典类型对话框
function closeTypeDialog() {
  typeDialogVisible.value = false
  typeFormRef.value?.resetFields()
}

// 提交字典类型表单
async function submitTypeForm() {
  await typeFormRef.value.validate()
  
  try {
    if (typeCurrentId.value) {
      // 更新字典类型
      await axios.put(`/api/dicts/types/${typeCurrentId.value}`, typeForm)
      ElMessage.success('更新字典类型成功')
    } else {
      // 创建字典类型
      await axios.post('/api/dicts/types', typeForm)
      ElMessage.success('创建字典类型成功')
    }
    closeTypeDialog()
    getDictTypes()
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.detail || error.message))
  }
}

// 删除字典类型
async function handleDeleteType(row) {
  await ElMessageBox.confirm(
    `确定要删除字典类型「${row.name}」吗？此操作将同时删除该类型下的所有字典项。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  try {
    await axios.delete(`/api/dicts/types/${row.id}`)
    ElMessage.success('删除字典类型成功')
    getDictTypes()
    
    // 如果当前正在编辑该类型的字典项，清空选择
    if (selectedDictType.value === row.id) {
      selectedDictType.value = null
      dictItemsData.value = []
    }
  } catch (error) {
    ElMessage.error('删除失败：' + (error.response?.data?.detail || error.message))
  }
}

// 处理字典类型状态变更
async function handleTypeStatusChange(row) {
  try {
    await axios.put(`/api/dicts/types/${row.id}`, {
      is_active: row.is_active
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 回滚状态
    row.is_active = !row.is_active
    ElMessage.error('状态更新失败：' + (error.response?.data?.detail || error.message))
  }
}

// 显示创建字典项对话框
function showCreateItemDialog() {
  itemCurrentId.value = null
  Object.assign(itemForm, {
    dict_type_id: selectedDictType.value,
    label: '',
    value: '',
    description: '',
    sort_order: 0,
    is_active: true
  })
  nextTick(() => {
    itemFormRef.value?.resetFields()
  })
  itemDialogVisible.value = true
}

// 显示编辑字典项对话框
function showEditItemDialog(row) {
  itemCurrentId.value = row.id
  Object.assign(itemForm, {
    dict_type_id: row.dict_type_id,
    label: row.label,
    value: row.value,
    description: row.description,
    sort_order: row.sort_order || 0,
    is_active: row.is_active
  })
  nextTick(() => {
    itemFormRef.value?.resetFields()
  })
  itemDialogVisible.value = true
}

// 关闭字典项对话框
function closeItemDialog() {
  itemDialogVisible.value = false
  itemFormRef.value?.resetFields()
}

// 提交字典项表单
async function submitItemForm() {
  await itemFormRef.value.validate()
  
  try {
    if (itemCurrentId.value) {
      // 更新字典项
      await axios.put(`/api/dicts/items/${itemCurrentId.value}`, itemForm)
      ElMessage.success('更新字典项成功')
    } else {
      // 创建字典项
      await axios.post('/api/dicts/items', itemForm)
      ElMessage.success('创建字典项成功')
    }
    closeItemDialog()
    getDictItems()
  } catch (error) {
    ElMessage.error('操作失败：' + (error.response?.data?.detail || error.message))
  }
}

// 删除字典项
async function handleDeleteItem(row) {
  await ElMessageBox.confirm(
    `确定要删除字典项「${row.label}」吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  try {
    await axios.delete(`/api/dicts/items/${row.id}`)
    ElMessage.success('删除字典项成功')
    getDictItems()
  } catch (error) {
    ElMessage.error('删除失败：' + (error.response?.data?.detail || error.message))
  }
}

// 处理字典项状态变更
async function handleItemStatusChange(row) {
  try {
    await service.put(`/dicts/items/${row.id}`, {
      is_active: row.is_active
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 回滚状态
    row.is_active = !row.is_active
    ElMessage.error('状态更新失败：' + (error.response?.data?.detail || error.message))
  }
}
</script>

<style scoped>
.dict-container {
  padding: 20px;
}

.mt-4 {
  margin-top: 16px;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.w-64 {
  width: 256px;
}

.gap-4 {
  gap: 16px;
}
</style>